const { query } = require('../config/database');
const Friend = require('./Friend');

class Chat {
  /**
   * 获取或创建会话
   * @param {string} userId - 当前用户ID
   * @param {string} friendId - 好友ID
   * @returns {Object} 会话信息
   */
  static async getOrCreateConversation(userId, friendId) {
    try {
      // 验证是否为好友关系
      const isFriend = await Friend.isFriend(userId, friendId);
      if (!isFriend) {
        throw new Error('只能与好友创建会话');
      }

      // 确保参与者按字典序排列，避免重复会话
      const participantOne = userId < friendId ? userId : friendId;
      const participantTwo = userId < friendId ? friendId : userId;

      // 查找现有会话
      const findSql = `
        SELECT 
          id,
          participant_one as participantOne,
          participant_two as participantTwo,
          last_message_time as lastMessageTime,
          created_at as createdAt
        FROM conversations 
        WHERE participant_one = ? AND participant_two = ? AND status = 1
      `;
      
      let conversations = await query(findSql, [participantOne, participantTwo]);
      
      if (conversations.length === 0) {
        // 创建新会话
        const createSql = `
          INSERT INTO conversations (participant_one, participant_two) 
          VALUES (?, ?)
        `;
        const result = await query(createSql, [participantOne, participantTwo]);
        
        // 获取新创建的会话
        conversations = await query(findSql, [participantOne, participantTwo]);
      }
      
      return conversations[0];
    } catch (error) {
      console.error('获取或创建会话失败:', error);
      throw error;
    }
  }

  /**
   * 发送消息
   * @param {number} conversationId - 会话ID
   * @param {string} senderId - 发送者ID
   * @param {string} content - 消息内容
   * @returns {Object} 消息信息
   */
  static async sendMessage(conversationId, senderId, content) {
    try {
      // 验证会话是否存在且用户有权限
      const conversationSql = `
        SELECT * FROM conversations 
        WHERE id = ? AND (participant_one = ? OR participant_two = ?) AND status = 1
      `;
      const conversations = await query(conversationSql, [conversationId, senderId, senderId]);
      
      if (conversations.length === 0) {
        throw new Error('会话不存在或无权限');
      }

      // 插入消息
      const insertSql = `
        INSERT INTO messages (conversation_id, sender_id, content) 
        VALUES (?, ?, ?)
      `;
      const result = await query(insertSql, [conversationId, senderId, content]);
      
      // 更新会话的最后消息时间
      const updateSql = `
        UPDATE conversations 
        SET last_message_time = CURRENT_TIMESTAMP 
        WHERE id = ?
      `;
      await query(updateSql, [conversationId]);
      
      // 获取刚插入的消息
      const messageSql = `
        SELECT 
          id,
          conversation_id as conversationId,
          sender_id as senderId,
          content,
          created_at as createdAt
        FROM messages 
        WHERE id = ?
      `;
      const messages = await query(messageSql, [result.insertId]);
      
      return messages[0];
    } catch (error) {
      console.error('发送消息失败:', error);
      throw error;
    }
  }

  /**
   * 获取会话消息列表
   * @param {number} conversationId - 会话ID
   * @param {string} userId - 用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 消息列表和分页信息
   */
  static async getMessages(conversationId, userId, page = 1, limit = 20) {
    try {
      // 确保参数为整数类型
      conversationId = parseInt(conversationId);
      page = parseInt(page);
      limit = parseInt(limit);
      
      // 验证用户是否有权限访问该会话
      const conversationSql = `
        SELECT * FROM conversations 
        WHERE id = ? AND (participant_one = ? OR participant_two = ?) AND status = 1
      `;
      const conversations = await query(conversationSql, [conversationId, userId, userId]);
      
      if (conversations.length === 0) {
        throw new Error('会话不存在或无权限');
      }

      const offset = (page - 1) * limit;
      
      // 获取消息列表（按时间倒序）
      const messagesSql = `
        SELECT 
          m.id,
          m.conversation_id as conversationId,
          m.sender_id as senderId,
          u.nick_name as senderNickName,
          u.avatar as senderAvatar,
          m.content,
          m.created_at as createdAt
        FROM messages m
        LEFT JOIN users u ON m.sender_id = u.user_id
        WHERE m.conversation_id = ?
        ORDER BY m.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `;
      
      const messages = await query(messagesSql, [conversationId]);
      
      // 获取总消息数
      const countSql = `SELECT COUNT(*) as total FROM messages WHERE conversation_id = ?`;
      const countResult = await query(countSql, [conversationId]);
      const total = countResult[0].total;
      
      return {
        messages: messages.reverse(), // 反转数组，使最新消息在最后
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取消息列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户会话列表
   * @param {string} userId - 用户ID
   * @returns {Array} 会话列表
   */
  static async getConversations(userId) {
    try {
      const sql = `
        SELECT 
          c.id,
          c.participant_one as participantOne,
          c.participant_two as participantTwo,
          c.last_message_time as lastMessageTime,
          c.created_at as createdAt,
          -- 获取对方用户信息
          CASE 
            WHEN c.participant_one = ? THEN u2.user_id
            ELSE u1.user_id
          END as otherUserId,
          CASE 
            WHEN c.participant_one = ? THEN u2.nick_name
            ELSE u1.nick_name
          END as otherUserNickName,
          CASE 
            WHEN c.participant_one = ? THEN u2.avatar
            ELSE u1.avatar
          END as otherUserAvatar,
          -- 获取最后一条消息
          m.content as lastMessage,
          m.sender_id as lastMessageSenderId
        FROM conversations c
        LEFT JOIN users u1 ON c.participant_one = u1.user_id
        LEFT JOIN users u2 ON c.participant_two = u2.user_id
        LEFT JOIN messages m ON c.id = m.conversation_id 
          AND m.created_at = (
            SELECT MAX(created_at) 
            FROM messages 
            WHERE conversation_id = c.id
          )
        WHERE (c.participant_one = ? OR c.participant_two = ?) AND c.status = 1
        ORDER BY c.last_message_time DESC, c.created_at DESC
      `;
      
      const conversations = await query(sql, [userId, userId, userId, userId, userId]);
      return conversations;
    } catch (error) {
      console.error('获取会话列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取会话详情
   * @param {number} conversationId - 会话ID
   * @param {string} userId - 用户ID
   * @returns {Object} 会话详情
   */
  static async getConversationDetail(conversationId, userId) {
    try {
      const sql = `
        SELECT 
          c.id,
          c.participant_one as participantOne,
          c.participant_two as participantTwo,
          c.last_message_time as lastMessageTime,
          c.created_at as createdAt,
          -- 获取对方用户信息
          CASE 
            WHEN c.participant_one = ? THEN u2.user_id
            ELSE u1.user_id
          END as otherUserId,
          CASE 
            WHEN c.participant_one = ? THEN u2.nick_name
            ELSE u1.nick_name
          END as otherUserNickName,
          CASE 
            WHEN c.participant_one = ? THEN u2.avatar
            ELSE u1.avatar
          END as otherUserAvatar
        FROM conversations c
        LEFT JOIN users u1 ON c.participant_one = u1.user_id
        LEFT JOIN users u2 ON c.participant_two = u2.user_id
        WHERE c.id = ? AND (c.participant_one = ? OR c.participant_two = ?) AND c.status = 1
      `;
      
      const conversations = await query(sql, [userId, userId, userId, conversationId, userId, userId]);
      
      if (conversations.length === 0) {
        throw new Error('会话不存在或无权限');
      }
      
      return conversations[0];
    } catch (error) {
      console.error('获取会话详情失败:', error);
      throw error;
    }
  }

  /**
   * 删除会话
   * @param {number} conversationId - 会话ID
   * @param {string} userId - 用户ID
   * @returns {boolean} 删除结果
   */
  static async deleteConversation(conversationId, userId) {
    try {
      // 验证用户是否有权限删除该会话
      const conversationSql = `
        SELECT * FROM conversations 
        WHERE id = ? AND (participant_one = ? OR participant_two = ?) AND status = 1
      `;
      const conversations = await query(conversationSql, [conversationId, userId, userId]);
      
      if (conversations.length === 0) {
        throw new Error('会话不存在或无权限');
      }

      // 软删除会话（将status设为0）
      const deleteSql = `
        UPDATE conversations 
        SET status = 0 
        WHERE id = ?
      `;
      await query(deleteSql, [conversationId]);
      
      return true;
    } catch (error) {
      console.error('删除会话失败:', error);
      throw error;
    }
  }
}

module.exports = Chat;